package zhihui.mobile.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.WindowManager;
import android.widget.Toast;

import com.zgm.utils.AppUtils;
import com.zgm.utils.UiUtils;
import com.zgm.utils.ui.LoadingDialog;

import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import zhihui.mobile.R;
import zhihui.mobile.app.MyApplication;
import zhihui.mobile.config.Config;
import zhihui.mobile.presenter.IPresenter;


/**
 * Created by 张公铭 on 2017/6/19 0019.
 * 基类Activity,所有业务界面都继承此BaseActivity
 */

public abstract class BaseFragmentActivity extends FragmentActivity implements IView
{

    protected LoadingDialog mLoadingDialog;
    private Handler mHandler;
    private Set<IPresenter> mAllPresenters = new HashSet<IPresenter>();
    private final int NET_CLOSE = -1, NET_NOT_WIFI = -2;

    /**
     * 获取布局文件ID
     */
    protected abstract int getLayoutResId();

    /**
     * 获取子类的Persenter,一个activity 可能会有多个persenter
     */
    protected abstract IPresenter[] getPresenters();

    /**
     * 初始化presenter
     */
    protected abstract void onInitPresenter();

    /**
     * 从intent 中解析数据，具体子类实现
     */
    protected void parseArgumentsFormIntent(Intent argIntent)
    {

    }

    private void addPresenters()
    {
        IPresenter[] presenters = getPresenters();
        if (presenters != null)
        {
            for (int i = 0; i < presenters.length; i++)
            {
                mAllPresenters.add(presenters[i]);
            }
        }
    }

    /**
     * 网络变化监听
     */
    private BroadcastReceiver mNetReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
            {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();

                if (netInfo != null && netInfo.isAvailable())
                {
                    if (netInfo.getType() != ConnectivityManager.TYPE_WIFI)
                    {
                        Message msg = new Message();
                        msg.what = NET_NOT_WIFI;
                        if (!Config.isEnable)
                        {
                            mHandler.sendMessage(msg);
                        }
                    }
                } else
                {
                    Message msg = new Message();
                    msg.what = NET_CLOSE;
                    mHandler.sendMessage(msg);
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        mHandler = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                switch (msg.what)
                {
                    case NET_CLOSE:
                        showNoNetDialog();
                        break;
                    case NET_NOT_WIFI:
                        showNetNoWifi();
                        break;
                }
            }
        };
        setContentView(getLayoutResId());
        addPresenters();
        onInitPresenter();
        if (getIntent() != null)
        {
            parseArgumentsFormIntent(getIntent());
        }
        initView();
        //是否锁屏
        if (!Config.isLockView)
        {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }

        //注册网络变化广播
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetReceiver, mFilter);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        JPushInterface.onResume(this);
        //没有网络提示用户
        if (!AppUtils.isNetworkConnected(this))
        {
            showNoNetDialog();
        }

        //提示不是wifi 是否继续使用
        if (!AppUtils.isWifiConnected(this))
        {
            showNetNoWifi();
        }

        for (IPresenter presenter : mAllPresenters)
        {
            if (presenter != null)
            {
                presenter.onResume();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

    }

    private void showNoNetDialog()
    {
        UiUtils.showDialog(this, "提示信息", "当前没有网络可用，请检查网络设置！", "确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                dialog.cancel();
                dialog = null;
            }
        }, null, null);
    }

    private void showNetNoWifi()
    {
        UiUtils.showDialog(this, "提示信息", "当前非WIFI网络状态，是否继续使用！", "继续", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Config.isEnable = true;
                dialog.dismiss();
                dialog.cancel();
                dialog = null;
            }
        }, "", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Config.isEnable = false;
                dialog.dismiss();
                dialog.cancel();
                dialog = null;
            }
        });
    }

    @Override
    protected void onStart()
    {
        super.onStart();
        for (IPresenter presenter : mAllPresenters)
        {
            if (presenter != null)
            {
                presenter.onStart();
            }
        }
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        JPushInterface.onPause(this);
        for (IPresenter presenter : mAllPresenters)
        {
            if (presenter != null)
            {
                presenter.onPause();
            }
        }
    }

    @Override
    protected void onStop()
    {
        super.onStop();
        for (IPresenter presenter : mAllPresenters)
        {
            if (presenter != null)
            {
                presenter.onStop();
            }
        }
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (mNetReceiver != null)
        {
            unregisterReceiver(mNetReceiver);
        }
        for (IPresenter presenter : mAllPresenters)
        {
            if (presenter != null)
            {
                presenter.onDestroy();
            }
        }
    }

    @Override
    public void showLoading()
    {
        if (mLoadingDialog == null)
        {
            mLoadingDialog = new LoadingDialog(this, R.drawable.loading_image);
        }
        mLoadingDialog.dismiss();
        mLoadingDialog.show();
    }

    @Override
    public void hindLoading()
    {
        if (mLoadingDialog != null)
        {
            mLoadingDialog.dismiss();
            mLoadingDialog = null;
        }
    }

    @Override
    public void destroyLoading()
    {
        if (mLoadingDialog != null)
        {
            mLoadingDialog.cancel();
            mLoadingDialog = null;
        }
    }

    @Override
    public void showMessage(String message)
    {
        UiUtils.ToastInCenter(this, message, Toast.LENGTH_SHORT);
    }

    @Override
    public void goBack(Class cls)
    {
        destroyLoading();
        MyApplication.finishActivity(cls);
    }
}
